# Copyright (c) 2021 Presto Labs Pte. Ltd.
# Author: yuxuan

import functools
import os

from coin.strategy.basis_strat.analysis.utils import get_strategy_config_from_script
from coin_deploy.basis_strat2.strat_list import PROD_STRATS as PROD_STRATS2


def get_all_strats_info(
    strategy_name=None,
    strategy_name_contains=None,
    strategy_type=None,
    trade_bases=None,
    trade_exchanges=None):
  coin_deploy_repo = os.environ.get('COIN_DEPLOY_REPO', 'coin_deploy')
  infos = []

  include_funcs = []
  if strategy_name:
    include_funcs.append(
        functools.partial(lambda strat_name, info: strat_name == info['name'], strategy_name))
  else:
    if strategy_name_contains:
      include_funcs.append(
          lambda info: strategy_name_contains in info['name'])
    if strategy_type:
      include_funcs.append(
          lambda info: info['group'].startswith(strategy_type))
    if trade_bases:
      include_funcs.append(
          lambda info: len(set(trade_bases).intersection(set([s.split('-')[0] for s in info['symbols']]))) > 0)
    if trade_exchanges:
      include_funcs.append(
          lambda info: info['exchange'] in trade_exchanges)

  for elem in PROD_STRATS2:
    strategy_name = elem['name']
    config, _ = get_strategy_config_from_script(coin_deploy_repo, strategy_name, True)
    machine = elem['host']
    trade_exchanges_info = []
    if strategy_name.startswith('basis_spread2') or strategy_name.startswith('mm_currency'):
      mea_keys = ['mea0', 'mea1']
      symbols_grp = \
          [[x['symbol'].split(':')[-1] for _, x in config['products'].items()],
           [x['hedge']['symbol'].split(':')[-1] for _, x in config['products'].items()]]
    elif strategy_name.startswith('mm_portfolio'):
      mea_keys = ['mea0']
      symbols_grp = \
          [[x['symbol'].split(':')[-1] for _, x in config['products'].items()]]
    else:
      mea_keys = ['mea']
      symbols_grp = [[x['trade_symbol'].split(':')[-1] for _, x in config['products'].items()]]
    for key in mea_keys:
      market_type, exchange, _ = config[key].split('.')
      trade_exchanges_info.append({'exchange': exchange, 'market_type': market_type,
                                   'mea': config[key]})

    for exch_info, symbols in zip(trade_exchanges_info, symbols_grp):
      info = elem.copy()
      info.update({
          'name': strategy_name,
          'host': machine,
          'exchange': exch_info['exchange'],
          'market_type': exch_info['market_type'],
          'mea': exch_info['mea'],
          'symbols': symbols,
          'driver': f'python/coin_deploy/basis_strat2/driver/{strategy_name}.json',
          'config': f'python/coin_deploy/basis_strat2/config/{strategy_name}.json'
      })
      include = True
      for func in include_funcs:
        if not func(info):
          include = False
          break
      if include:
        infos.append(info)
  return infos
